/*************************************************************************
 * File Name:    NQueens.cc
 * Author:       zero91
 * Mail:         jianzhang9102@gmail.com
 * Created Time: 2013/11/4 10:33:08
 * 
 * Description:  
 |------------------------------------------------------------------------
 | Problem: NQueen
 | Given an integer n, return all distinct solutions to the n-queens puzzle.
 |
 | Each solution contains a distinct board configuration of the n-queens' placement,
 | where 'Q' and '.' both indicate a queen and an empty space respectively.
 |
 | For example,
 | There exist two distinct solutions to the 4-queens puzzle:
 |
 | [
 |   [".Q..",  // Solution 1
 |    "...Q",
 |    "Q...",
 |    "..Q."],
 |
 |   ["..Q.",  // Solution 2
 |    "Q...",
 |    "...Q",
 |    ".Q.."
 |   ]
 | ]
 |------------------------------------------------------------------------
 ************************************************************************/

#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <deque>
#include <map>
#include <set>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>

using namespace std;

class Solution {
private:
    bool can_place(const vector<int> &row, int k)
    {
        for (int i = 0; i < k; ++i) {
            if (row[i] == row[k] || abs(row[i] - row[k]) == k - i) {
                return false;
            }
        }
        return true;
    }
    
    void add_solution(vector<vector<string> > &ans, const vector<int> &row)
    {
        vector<string> sol;
        string rq;
        
        for (size_t i = 0; i < row.size(); ++i) {
            rq = "";
            for (size_t j = 0; j < row.size(); ++j) {
                rq += (j == row[i]) ? "Q" : ".";
            }
            sol.push_back(rq);
        }
        ans.push_back(sol);
    }

public:
    vector<vector<string> > solveNQueens(int n)
    {
        vector<vector<string> > ans;
        
        int k;
        vector<int> row(n, -1);
        k = 0;
        row[0] = -1;
        while (k >= 0) {
            while (++row[k] < n && !can_place(row, k));
            
            if (row[k] < n) {
                if (k == n - 1) {
                    add_solution(ans, row);
                    --k;
                } else {
                    row[++k] = -1;
                }
            } else {
                --k;
            }
        }
        return ans;
    }
};

int
main(int argc, char *argv[])
{
    Solution sol;

    vector<vector<string> > ans = sol.solveNQueens(4);

    for (size_t i = 0; i < ans.size(); ++i) {
        for (size_t j = 0; j < ans[i].size(); ++j) {
            cout << ans[i][j] << endl;
        }
        cout << endl;
    }

    return 0;
}
